using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace Decav.Gatsb.Web.Controls
{
    /// <summary>
    /// Renders a historical list of <see cref="Post"/> grouped by <see cref="Location"/>.
    /// </summary>
    public class HistoricalLocationRepeater : BaseDataBoundControl
    {
        /// <summary>
        /// Gets or sets the size of the image to place next to image posts.
        /// </summary>
        public UserImageSize ImageSize
        {
            get
            {
                if (ViewState["ImageSize"] == null)
                    return UserImageSize.Thumbnail;
                else
                    return (UserImageSize)ViewState["ImageSize"];
            }
            set
            {
                ViewState["ImageSize"] = value;
            }
        }

        /// <summary>
        /// Gets or sets how a persons name on a post will be formatted.
        /// </summary>
        public NameFormat PersonNameFormat
        {
            get
            {
                if (ViewState["PersonNameFormat"] == null)
                    return NameFormat.FirstName;

                return (NameFormat)ViewState["PersonNameFormat"];
            }
            set
            {
                ViewState["PersonNameFormat"] = value;
            }
        }

        protected override void PerformSelect()
        {
        }

        protected override void ValidateDataSource(object dataSource)
        {
            if (dataSource == null)
                return;

            if (!(dataSource is IEnumerable<Post>))
                throw new ArgumentException("The data source specified is not an IEnumerable of type Post.");
        }

        private List<Post> _currentRender;

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            AddAttributesToRender(writer);
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
            writer.RenderEndTag();
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (DataSource == null)
            {
                this.Visible = false;
            }
            else
            {
                // Prepare the rendering by creating a list of the items to render, putting them in the proper order
                _currentRender = new List<Post>((IEnumerable<Post>)DataSource);
                _currentRender.Sort(ReverseComparePostDates);
            }

            base.OnPreRender(e);
        }

        private int ReverseComparePostDates(Post x, Post y)
        {
            if (x.CreateDate < y.CreateDate)
                return 1;
            else if (x.CreateDate > y.CreateDate)
                return -1;

            return 0;
        }

        protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
            base.RenderContents(writer);
        }

        protected override void RenderChildren(System.Web.UI.HtmlTextWriter writer)
        {
            Guid lastLocation = Guid.Empty;
            bool inul = false;
            foreach (Post post in _currentRender)
            {
                DateTime curPostDate = post.CreateDate.Date;

                // Render a header above a change in dates.
                if (lastLocation != post.LocationId)
                {
                    if (inul)
                        writer.RenderEndTag(); // ul
                    
                    RenderHeader(post.Location, curPostDate, writer);
                    writer.RenderBeginTag(HtmlTextWriterTag.Ul);
                    inul = true;
                }

                lastLocation = post.LocationId;

                // Render the individual item
                RenderItem(post, writer);
            }

            if (inul)
                writer.RenderEndTag(); // ul

            base.RenderChildren(writer);
        }

        private void RenderItem(Post post, HtmlTextWriter writer)
        {
            PostRenderer renderer = new PostRenderer(writer, HtmlTextWriterTag.Li);
            renderer.NameFormat = PersonNameFormat;
            renderer.RenderSummary(post);
        }

        private void RenderHeader(Location location, DateTime date, HtmlTextWriter writer)
        {
            writer.RenderBeginTag(HtmlTextWriterTag.H4);
            writer.Write("@");
            PostRenderer.RenderLocationName(writer, location);
            writer.Write(" ({0})", StringFormatting.ToFriendlyDate(date));
            writer.RenderEndTag(); // h4
        }
    }
}
